package com.example.demo.Service.impl;

import com.example.demo.Dao.QuestionMapper;
import com.example.demo.Entity.Disease;
import com.example.demo.Entity.Question;
import com.example.demo.Service.QuestionService;
import com.example.demo.Vo.QuestionAndScore;
import com.example.demo.vec.Word2VEC;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

@Service
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private Word2VEC vec;
    @Override
    //@Cacheable(value="question")
    public List<Question> findAll() {
        System.out.println("数据库查询");
        return questionMapper.findAll();
    }


    @Override
    public Question findById(Integer id) {
        return questionMapper.findById(id);
    }

    @Override
    public QuestionAndScore get_most_sim(String question) {
        long start=System.currentTimeMillis();

        List<Question> list=findAll();
        Queue<QuestionAndScore> queue=new PriorityQueue<QuestionAndScore>(10,new Comparator<QuestionAndScore>() {
            @Override
            public int compare(QuestionAndScore o1, QuestionAndScore o2) {
                return Double.compare(o2.getScore(),o1.getScore());
            }
        });

        for(Question q:list){
            queue.add(new QuestionAndScore(q,vec.cos_sim(question,q.getQuestion())));
        }
        QuestionAndScore peek=new QuestionAndScore(queue.peek().getQuestion(),queue.peek().getScore());
        for(int i=0;i<11;i++){
            System.out.println(queue.peek().getQuestion().toString());
            System.out.println(queue.peek().getScore());
            if(i>0){
                if(queue.peek().getScore()>0.6){
                        peek.append(queue.peek().getQuestion());
                }
            }
            queue.poll();
        }
        long end=System.currentTimeMillis();
        System.out.println(end-start);
        return peek;
    }

    @Override
    public void deleteQuestion(Integer qid) {
            questionMapper.deleteQuestion(qid);
    }

    @Override
    public void updateQuestion(Integer qid, String question, String answer) {
        questionMapper.updateQuestion(qid,question,answer);
    }

    @Override
    public void addQuestion(String question, String answer) {
        questionMapper.addQuestion(question,answer);
    }
    @Override
    public PageInfo<Question> findPageByName(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Question> list=findAll();
        PageInfo<Question> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }
}
